//
//  HubuQueryViewController.m
//  iHubu2
//
//  Created by hanshui on 12-10-31.
//  Copyright (c) 2012年 hanshui. All rights reserved.
//

#import "HubuQueryViewController.h"
#import "ASIHTTPRequest.h"
#import "RegexKitLite.h"
#import "STUtils.h"
#import "OPACConstant.h"
#import "OPACBookObjects.h"
#import "LibraryBookCustomCell.h"
#import "HubuQueryDetailViewController.h"

@interface HubuQueryViewController ()

@end

@implementation HubuQueryViewController
@synthesize resultTotal, keywords1, searchListTableView, currentPage;
@synthesize resultTotalLabel, waitingView,notDataReturnLabel;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    if(bookObjectArray == nil) {
        bookObjectArray = [[NSMutableArray alloc] initWithCapacity:10];
    }
    self.currentPage = 1;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//本馆没有您检索的馆藏书目

- (void)requestCompleted:(ASIHTTPRequest *)request
{
    NSMutableData *webData = [[NSMutableData alloc] init];
    [webData appendData:[request responseData]];
    NSString *theXML = [[NSString alloc] initWithBytes:[webData mutableBytes]
												length:[webData length]
											  encoding:NSUTF8StringEncoding];
    //    NSLog(@"webData:%@", theXML);
    //    NSLog(@"webData2:%@", [OPACViewController replaceUnicode:theXML]);
    //    NSString *responseString = [[request responseString] dataUsingEncoding:NSUTF8StringEncoding];
    //    NSLog(@"responseString:%@", responseString);
    [self clearHTMLData2Array:theXML];
    
}

- (void)requestError:(ASIHTTPRequest *)request {
    NSError *error = [request error];
    NSLog(@"error:%@", error);
//    UIAlertView *loginAlertView = [[UIAlertView alloc] initWithTitle:@"提示"
//                                                             message:@"数据错误，如多次出现请联系管理员。"
//                                                            delegate:self
//                                                   cancelButtonTitle:@"关闭"
//                                                   otherButtonTitles:nil, nil];
//    [loginAlertView show];
//    [loginAlertView release];
    
    [waitingView stopAnimating];
}

- (void) showNotDataReturn {
    [waitingView stopAnimating];
    [notDataReturnLabel setHidden:NO];
}

- (void) clearHTMLData2Array:(NSString *) sourceCode {
    if ( sourceCode == nil || [sourceCode isEqualToString:@""]) {
        [self showNotDataReturn];
        return;
    }
    
    if( bookListArray == nil) {
        bookListArray = [[NSMutableArray alloc] initWithCapacity:10];
    } else {
        [bookListArray removeAllObjects];
    }
    
    //判断是否查询到图书
    if ([sourceCode rangeOfString:NO_RETURN_BOOK].location != NSNotFound) {
        //NSLog(@"没有查询到相关图书\n");
        //logInfo = @"没有查询到相关图书";
        [self showNotDataReturn];
        return;
    }
    
    //获取纪录条数
    NSRange range = [sourceCode rangeOfString:RESULT_TOTAL];
    NSRange totalBegin, totalEnd;
    
    totalBegin = [sourceCode rangeOfString:@">" options:nil range:NSMakeRange(range.location, sourceCode.length- range.location - 1)];
    if(totalBegin.location != NSNotFound) {
        totalEnd = [sourceCode rangeOfString:@"<" options:nil range:NSMakeRange(totalBegin.location, sourceCode.length - totalBegin.location - 1)];
    }
    if(totalEnd.location != NSNotFound) {
        if((totalBegin.location + totalBegin.length) < totalEnd.location) {
            self.resultTotal = [sourceCode substringWithRange:NSMakeRange(totalBegin.location + totalBegin.length, totalEnd.location - totalBegin.location - totalBegin.length)];
            
            //NSLog(@"resultTotal:%@", self.resultTotal);
            resultTotalLabel.text = self.resultTotal;
        }
    }
    
    //获取每一本图书信息
    int rangeLocation = totalEnd.location;
    NSRange listBooksBegin = [sourceCode rangeOfString:DIV_LIST_BOOKS_BEGIN options:nil range:NSMakeRange(rangeLocation, sourceCode.length - rangeLocation)];
    int i = 0;
    while ((listBooksBegin.location != NSNotFound)) {
        NSRange listBooksEnd = [sourceCode rangeOfString:DIV_LIST_BOOKS_END options:nil range:NSMakeRange(listBooksBegin.location, sourceCode.length - listBooksBegin.location)];
        //NSLog(@"item[%d]=%@", i++, [sourceCode substringWithRange:NSMakeRange(listBooksBegin.location, listBooksEnd.location - listBooksBegin.location + listBooksEnd.length)]);
        
        [bookListArray addObject:[sourceCode substringWithRange:NSMakeRange(listBooksBegin.location, listBooksEnd.location - listBooksBegin.location + listBooksEnd.length)]];
        
        listBooksBegin = [sourceCode rangeOfString:DIV_LIST_BOOKS_BEGIN options:nil range:NSMakeRange(listBooksEnd.location, sourceCode.length - listBooksEnd.location)];
    }
    
    //处理图书信息到对象
    [self bookList2BookObject];
    
}

/*
 <div class="list_books" id="list_books">
 
 <h3><span class="doc_type_class">中文图书</span><a href="item.php?marc_no=0001498848">20.&#x65b0;&#x7535;&#x8111;&#x8bfe;&#x5802;&#x002e;&#x4e94;&#x7b14;&#x5b9e;&#x7528;&#x7bc7;</a>      &#x0054;&#x0050;&#x0033;&#x0039;&#x0031;&#x002e;&#x0031;&#x0034;&#x002f;&#x0036;&#x0036;&#x0038; </h3>
 <p>
 <span><strong>馆藏复本：</strong>1 <br />
 <strong>可借复本：</strong>1 </span>
 &#x672c;&#x4e66;&#x7f16;&#x59d4;&#x4f1a;&#x7f16;&#x8457; <br />
 &#x7535;&#x5b50;&#x5de5;&#x4e1a;&#x51fa;&#x7248;&#x793e;&nbsp;&#x0032;&#x0030;&#x0030;&#x0033;
 </p>
 </div>
 */
- (void) bookList2BookObject {
    if( bookListArray != nil && [bookListArray count] > 0) {
        if(bookObjectArray == nil) {
            bookObjectArray = [[NSMutableArray alloc] initWithCapacity:10];
        }
        for(int i=0; i<[bookListArray count]; i++) {
            OPACBookObjects *opac = [[OPACBookObjects alloc] init];
            
            //类型
            NSRange spanDocTypeBegin = [[bookListArray objectAtIndex:i] rangeOfString:SPAN_DOC_TYPE_CLASS_BEGIN];
            NSRange spanDocTypeEnd = [[bookListArray objectAtIndex:i] rangeOfString:SPAN_DOC_TYPE_CLASS_END];
            [opac setBookType: [[bookListArray objectAtIndex:i] substringWithRange:NSMakeRange(spanDocTypeBegin.location + spanDocTypeBegin.length, spanDocTypeEnd.location - (spanDocTypeBegin.location + spanDocTypeBegin.length))]];
            
            //MARC NO
            NSRange marcNoBegin = [[bookListArray objectAtIndex:i] rangeOfString:A_MARC_NO_BEGIN];
            NSRange marcNoEnd = [[bookListArray objectAtIndex:i] rangeOfString:A_MARC_NO_END options:nil range:NSMakeRange(marcNoBegin.location, [[bookListArray objectAtIndex:i] length]  - marcNoBegin.location)];
            [opac setMarcNo: [[bookListArray objectAtIndex:i] substringWithRange:NSMakeRange(marcNoBegin.location + marcNoBegin.length, marcNoEnd.location - (marcNoBegin.location + marcNoBegin.length))]];
            
            //TITLE
            NSRange titleEnd = [[bookListArray objectAtIndex:i] rangeOfString:A_END options:nil range:NSMakeRange(marcNoEnd.location, [[bookListArray objectAtIndex:i] length]  - marcNoEnd.location)];
            [opac setBookTitle: [[bookListArray objectAtIndex:i] substringWithRange:NSMakeRange(marcNoEnd.location + marcNoEnd.length, titleEnd.location - (marcNoEnd.location + marcNoEnd.length))]];
            [opac setBookTitle:[HubuQueryViewController replaceUnicode:opac.bookTitle]];
            
            //Sieral
            NSRange serialEnd = [[bookListArray objectAtIndex:i] rangeOfString:SERIAL_END options:nil range:NSMakeRange(titleEnd.location, [[bookListArray objectAtIndex:i] length]  - titleEnd.location)];
            [opac setBookSerial: [[bookListArray objectAtIndex:i] substringWithRange:NSMakeRange(titleEnd.location + titleEnd.length, serialEnd.location - (titleEnd.location + titleEnd.length))]];
            [opac setBookSerial:[HubuQueryViewController replaceUnicode:opac.bookSerial]];
            
            //bookCopiedCount
            NSRange bookCopiedCountBegin = [[bookListArray objectAtIndex:i] rangeOfString:LIBRARY_COPIED_ALL_BEGIN];
            NSRange bookCopiedCountEnd = [[bookListArray objectAtIndex:i] rangeOfString:LIBRARY_COPIED_ALL_END options:nil range:NSMakeRange(bookCopiedCountBegin.location, [[bookListArray objectAtIndex:i] length]  - bookCopiedCountBegin.location)];
            [opac setBookCopiedCount: [[bookListArray objectAtIndex:i] substringWithRange:NSMakeRange(bookCopiedCountBegin.location + bookCopiedCountBegin.length, bookCopiedCountEnd.location - (bookCopiedCountBegin.location + bookCopiedCountBegin.length))]];
            
            //bookRentalCount
            NSRange bookRentalCountBegin = [[bookListArray objectAtIndex:i] rangeOfString:LIBRARY_COPIED_RENT_BEGIN];
            NSRange bookRentalCountEnd = [[bookListArray objectAtIndex:i] rangeOfString:LIBRARY_COPIED_RENT_END options:nil range:NSMakeRange(bookRentalCountBegin.location, [[bookListArray objectAtIndex:i] length]  - bookRentalCountBegin.location)];
            [opac setBookRentalCount: [[bookListArray objectAtIndex:i] substringWithRange:NSMakeRange(bookRentalCountBegin.location + bookRentalCountBegin.length, bookRentalCountEnd.location - (bookRentalCountBegin.location + bookRentalCountBegin.length))]];
            
            //author
            NSRange authorEnd = [[bookListArray objectAtIndex:i] rangeOfString:MEMO_SPLIT options:nil range:NSMakeRange(bookRentalCountEnd.location, [[bookListArray objectAtIndex:i] length]  - bookRentalCountEnd.location)];
            [opac setBookAuthor: [[bookListArray objectAtIndex:i] substringWithRange:NSMakeRange(bookRentalCountEnd.location + bookRentalCountEnd.length, authorEnd.location - (bookRentalCountEnd.location + bookRentalCountEnd.length))]];
            [opac setBookAuthor:[HubuQueryViewController replaceUnicode:opac.bookAuthor]];
            
            //press
            NSRange pressEnd = [[bookListArray objectAtIndex:i] rangeOfString:MEMO_END options:nil range:NSMakeRange(authorEnd.location, [[bookListArray objectAtIndex:i] length]  - authorEnd.location)];
            [opac setBookPress: [[bookListArray objectAtIndex:i] substringWithRange:NSMakeRange(authorEnd.location + authorEnd.length, pressEnd.location - (authorEnd.location + authorEnd.length))]];
            [opac setBookPress:[HubuQueryViewController replaceUnicode:opac.bookPress]];
            
            [bookObjectArray addObject:opac];
            
            [opac toString];
            //[opac release];
        }
        [self.searchListTableView reloadData];
    } else {
        [self showNotDataReturn];
    }
    [waitingView stopAnimating];
    
}

+ (NSString *)replaceUnicode:(NSString *)unicodeStr {
	
	NSString *tempStr1 = [unicodeStr stringByReplacingOccurrencesOfString:@"&#x" withString:@"\\U"];
    tempStr1 = [tempStr1 stringByReplacingOccurrencesOfString:@"&nbsp;" withString:@" "];
    tempStr1 = [tempStr1 stringByReplacingOccurrencesOfString:@";" withString:@""];
    //NSString *tempStr1 = [tempStr1 stringByReplacingOccurrencesOfRegex:@"&#x[a-z0-9]{4};" withString:@"abc"];
	NSString *tempStr2 = [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
	NSString *tempStr3 = [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
	NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
	NSString* returnStr = [NSPropertyListSerialization propertyListFromData:tempData
                                                           mutabilityOption:NSPropertyListImmutable
                                                                     format:NULL
                                                           errorDescription:NULL];
	
	//NSLog(@"Output = %@", returnStr);
	
	return [[returnStr stringByReplacingOccurrencesOfString:@"\\r\\n" withString:@"\n"] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}


-(void) showSearchListInfo:(NSString *) keywords {
    if(![self isViewLoaded]){
        [self loadView];
    }
    
    //NSLog(@"keyword:%@", keywords);
    self.currentPage = 1;
    
    self.keywords1 = keywords;
    //第一次正确查询
    NSURL *url = [NSURL URLWithString:[[NSString stringWithFormat:@"http://59.68.64.61:8080/opac/openlink.php?strSearchType=title&historyCount=1&strText=%@&x=0&y=0&doctype=ALL&match_flag=forward&displaypg=20&sort=CATA_DATE&orderby=desc&showmode=list&dept=ALL", keywords] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    
    //第二次正确查询
//    NSURL *url = [NSURL URLWithString:[[NSString stringWithFormat:@"http://59.68.64.61:8080/opac/openlink.php?dept=ALL&title=%@&doctype=ALL&lang_code=ALL&match_flag=forward&displaypg=20&showmode=list&orderby=DESC&sort=CATA_DATE&onlylendable=no&count=2634&page=2", keywords] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    
    [request setDidFinishSelector:@selector(requestCompleted:)];
    [request setDidFailSelector:@selector(requestError:)];
    
    [request setDelegate:self];
    [request startAsynchronous];
}

-(void) showSearchListInfoMore {
    //第一次正确查询
//    NSURL *url = [NSURL URLWithString:[[NSString stringWithFormat:@"http://59.68.64.61:8080/opac/openlink.php?strSearchType=title&historyCount=1&strText=%@&x=0&y=0&doctype=ALL&match_flag=forward&displaypg=20&sort=CATA_DATE&orderby=desc&showmode=list&dept=ALL", keywords] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    
    //NSLog(@"currentPage:%d", self.currentPage);
    //NSLog(@"currentPage:%@", self.keywords1);
    //NSLog(@"currentPage:%@", self.resultTotal);
    //NSLog(@"currentPage:%d-%@-%@", self.currentPage, self.keywords1, self.resultTotal);
    self.currentPage += 1;
    //NSLog(@"currentPage:%d-%@-%@", self.currentPage, self.keywords1, self.resultTotal);
    
    
    //第二次正确查询
    NSURL *url = [NSURL URLWithString:[[NSString stringWithFormat:@"http://59.68.64.61:8080/opac/openlink.php?dept=ALL&title=%@&doctype=ALL&lang_code=ALL&match_flag=forward&displaypg=20&showmode=list&orderby=DESC&sort=CATA_DATE&onlylendable=no&count=%@&page=%d", keywords1, resultTotal, self.currentPage] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    
    [request setDidFinishSelector:@selector(requestCompleted:)];
    [request setDidFailSelector:@selector(requestError:)];
    
    [request setDelegate:self];
    [request startAsynchronous];
}

-(IBAction)backClick:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark -
#pragma mark Table View Data Source Methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    //NSLog(@"bookCount:%d", [bookObjectArray count]);
    return [bookObjectArray count];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    /*
    static NSString *CellTableIdentifier = @"CellTableIdentifier";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
                             CellTableIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                       reuseIdentifier: CellTableIdentifier] autorelease];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.textLabel.font = [UIFont systemFontOfSize:18];
    cell.textLabel.textColor = [UIColor colorWithRed:0.2 green:0.4 blue:0.4 alpha:1.0];
    OPACBookObjects *opacItem = [bookObjectArray objectAtIndex:[indexPath row]];
    cell.textLabel.text = [opacItem.bookTitle stringByReplacingOccurrencesOfRegex:@"&#[0-9]{4};" withString:@" "];
    
    
    return cell;
     */
    static NSString *CellTableIdentifier = @"CellTableIdentifier1";
    LibraryBookCustomCell *cell = (LibraryBookCustomCell *)[tableView dequeueReusableCellWithIdentifier:
                                                  CellTableIdentifier];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"LibraryBookCustomCell" owner:self options:nil] objectAtIndex:0];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    OPACBookObjects *opacItem = [bookObjectArray objectAtIndex:[indexPath row]];
    cell.title.textColor = [UIColor colorWithRed:0.2 green:0.4 blue:0.4 alpha:1.0];
    cell.title.text = [NSString stringWithFormat:@"%@ (%@)", [opacItem.bookTitle stringByReplacingOccurrencesOfRegex:@"&#[0-9]{4};" withString:@" "], opacItem.bookSerial];
    cell.author.text = opacItem.bookAuthor;
    cell.press.text = opacItem.bookPress;
    cell.copied.text = opacItem.bookCopiedCount;
    cell.renter.text = opacItem.bookRentalCount;
    if([opacItem.bookType isEqualToString:@"西文图书"]) {
        cell.type.text = @"西";
    }
    
    return cell;
}

 -(float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
     return 77;
 }

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    HubuQueryDetailViewController *hubuQueryDetailViewController = [[HubuQueryDetailViewController alloc] initWithNibName:@"HubuQueryDetailViewController" bundle:nil];

    OPACBookObjects *opacItem = [bookObjectArray objectAtIndex:[indexPath row]];
    [hubuQueryDetailViewController showBookInfo:opacItem.marcNo title:opacItem.bookTitle];
    
    //NSDate *object = _objects[indexPath.row];
    //self.detailViewController.detailItem = object;
    [self.navigationController pushViewController:hubuQueryDetailViewController animated:YES];
    [hubuQueryDetailViewController release];
    
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if(([indexPath row] + 1) == [bookObjectArray count]){
        if(([indexPath row] + 1) >= [self.resultTotal intValue]) {
            return;
        }
        [waitingView startAnimating];
        [self showSearchListInfoMore];
    }
}


-(IBAction)nextPageClick:(id)sender {
    [waitingView startAnimating];
    [self showSearchListInfoMore];
}
@end
